package webservices.helper;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class Helper {
	public static Connection getDBConnection(){
		try {
			Class.forName("com.mysql.jdbc.Driver");
			return DriverManager.getConnection("jdbc:mysql://localhost/soa?user=root&password=root&useUnicode=true&characterEncoding=UTF-8");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static String paramStr(String name, String value){
		return "<param name='" + name + "' value='" + value + "' />";
	}
	
	public static NodeList getResponse(String responseXML) throws ParserConfigurationException, UnsupportedEncodingException, SAXException, IOException{
		DocumentBuilderFactory documentFactory=DocumentBuilderFactory.newInstance();
		DocumentBuilder builder;
		builder = documentFactory.newDocumentBuilder();
		Document doc = builder.parse(new ByteArrayInputStream(responseXML.getBytes("utf8")));
		NodeList responseNodeList = doc.getElementsByTagName("response");
		
		return responseNodeList;
	}
	
	public static String getParam(HttpServletRequest request, String name){
		String str = request.getParameter(name);
		
//		if (str != null){
//			try {
//				return new String(str.getBytes("ISO-8859-1"), "utf-8");
//			} catch (UnsupportedEncodingException e) {
//				e.printStackTrace();
//			}
//		}else {
//			str = "";
//		}
		return str;
	}
	
	public static String decodeUtf8(String str){
		if (str != null){
			try {
				return new String(str.getBytes("ISO-8859-1"), "utf-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}else {
			str = "";
		}
		return str;
	}
}
